const cartModel = require('../models/cart')
async function addcart(data, callback) {
	const xx = {
		gooods_id: data.gooods_id,
		username: data.username,
	}
	const p = await new Promise((resolve, rej) => {
		cartModel.getcart(xx, (err, res) => {
			resolve({ err, res })
		})
	})
	console.log('p======', p)
	if (p.res.length) {
		console.log('data.qty----------', p.res[0].qty)
		data.qty = p.res[0].qty * 1 + 1
		const { qty, goods_id, username } = data
		const xx = {
			qty,
			goods_id,
			username,
		}
		cartModel.updatecart(xx, (err, res) => {
			if (!err) {
				callback({
					code: 200,
					msg: '添加成功',
				})
			} else {
				callback({
					code: 400,
					err,
					msg: '添加失败',
				})
			}
		})
	} else {
		data.qty = '1'
		cartModel.addcart(data, (err, res) => {
			if (!err) {
				callback({
					code: 200,
					msg: '添加成功',
				})
			} else {
				callback({
					code: 400,
					msg: '添加失败',
				})
			}
		})
	}
}
function updatecart(data, callback) {
	cartModel.updatecart(data, (err, res) => {
		if (!err) {
			callback({
				code: 200,
				msg: '修改成功',
			})
		} else {
			callback({
				code: 400,
				msg: '修改失败',
			})
		}
	})
}
function delcart(data, callback) {
	cartModel.delcart(data, (err, res) => {
		if (!err) {
			callback({
				code: 200,
				msg: '删除成功',
			})
		} else {
			callback({
				code: 400,
				msg: '删除失败',
			})
		}
	})
}
function getcart(data, callback) {
	cartModel.getcart(data, (err, res) => {
		if (res) {
			callback({
				code: 200,
				data: res,
				msg: '获取成功',
			})
		} else {
			callback({
				code: 400,
				err,
				msg: '获取失败',
			})
		}
	})
}
module.exports = {
	addcart,
	getcart,
	updatecart,
	delcart,
}
